const dayjs = require("dayjs")
const { query } = require("../util/dbutil")
const { AssertUtils, IdUtils, RandomUtils } = require("../util/utils")
const sqlWhere = require("../util/SqlWhere");
const sqlUpdate = require("../util/SqlUpdate");

function queryIsEmpty(data) {
    const {name, address, voltage, status, kw,km} = data
    AssertUtils.StringNotEmpty(name, "充电桩名称不能为空")
    AssertUtils.StringNotEmpty(address, "充电桩地址不能为空")
    AssertUtils.StringNotEmpty(voltage, "充电桩电压不能为空")
    AssertUtils.StringNotEmpty(status, "充电桩状态不能为空")
    if(!status.includes(['空闲','运行中','报警'])){
        AssertUtils.StringNotEmpty(status, "充电桩状态只能为空闲/运行中/报警")
    }
    AssertUtils.StringNotEmpty(kw, "充电桩功率不能为空")
    AssertUtils.StringNotEmpty(km, "充电桩距离不能为空")
}
/**
 * 查询充电桩列表
 * @params {array} [id,name,address,status]
 * @returns
 */
const getChargePileList = async (query) => {
    const arr = ['id','%name%','%address%','%status%']
    const data = await new sqlWhere(`select * from charging_stations`, query)
        .addQueryCriteriaMultiple(arr)
        .setPagination()
        .executeTheQuery()
    const result = await new sqlWhere('SELECT COUNT(*) AS count FROM charging_stations',query)
        .addQueryCriteriaMultiple(arr)
        .executeTheQuery()
    return {
        data,
        result
    }
}

/**
 * 创建充电桩
 * @params {array} data [name,address,voltage,status,img,kw,km]
 * @returns 
 */
const addChargePile = async (data) => {
    queryIsEmpty(data)
    const keyArr = Object.keys(data)
    const valArr = Object.values(data)
    const arr = Object.keys(data).fill('?').join()
    console.log(`insert into charging_stations (${keyArr.join()}) values (${arr})`)
    return await query(`insert into charging_stations (${keyArr.join()}) values (${arr})`,valArr)
}
const updateChargePile = async (data) => {
    AssertUtils.StringNotEmpty(data.id, "id不能为空")
    return await new sqlUpdate(`update charging_stations set`,data)
        .setSearchCriteria(Object.keys(data))
        .setQueryCriteria(`where id=${data.id}`)
        .execUpdate()
}

const deleteChargePile = async (id) => {
    AssertUtils.StringNotEmpty(id, "充电桩id不能为空")
    return await query(`DELETE FROM charging_stations WHERE id = ?`,[id])
}


module.exports = {
    addChargePile,
    updateChargePile,
    deleteChargePile,
    getChargePileList
}
